package com.sky.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;


    @Transactional
    public Long save(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);

        // 关键修改：插入的是 Setmeal 对象，而非 SetmealDTO
        setmealMapper.insert(setmeal);

        Long setmealId = setmeal.getId();
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        if (setmealDishes != null && !setmealDishes.isEmpty()) {
            setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(setmealId));
            setmealDishMapper.insertBatch(setmealDishes);

        }

        return setmealId;
    }

    @Override
    public PageResult pageQuery(SetmealPageQueryDTO setmealPageQueryDTO) {
        log.info("分页查询套餐：{}", setmealPageQueryDTO);

        // 设置分页参数
        PageHelper.startPage(setmealPageQueryDTO.getPage(), setmealPageQueryDTO.getPageSize());

        // 查询数据
        List<Setmeal> setmeals = setmealMapper.pageQuery(setmealPageQueryDTO);

        // 将Setmeal转换为SetmealVO
        List<SetmealVO> setmealVOS = setmeals.stream()
                .map(setmeal -> {
                    SetmealVO setmealVO = new SetmealVO();
                    BeanUtils.copyProperties(setmeal, setmealVO);
                    return setmealVO;
                })
                .collect(Collectors.toList());

        // 创建PageInfo对象
        PageInfo<SetmealVO> pageInfo = new PageInfo<>(setmealVOS);

        return new PageResult(pageInfo.getTotal(), pageInfo.getList());

    }

    //批量删除套餐
    public void deleteBatch(List<Long> ids) {
        // 检查套餐是否可删除（如启售状态不可删）
        if (!checkCanDelete(ids)) {
            throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
        }

        // 删除套餐数据
        setmealMapper.deleteByIds(ids);

        // 删除关联的套餐菜品关系
        setmealDishMapper.deleteBySetmealIds(ids);
    }


    private boolean checkCanDelete(List<Long> ids) {
        // 示例校验逻辑：检查是否有启售中的套餐
        return setmealMapper.selectOnSaleCount(ids) == 0;

    }

    @Override
    public void saveWithDish(SetmealDTO setmealDTO) {

    }
    // 修改套餐及菜品
    @Transactional
    public void updateWithDishes(SetmealDTO setmealDTO) {
        Setmeal setmeal = setmealMapper.getById(setmealDTO.getId());

        // 状态校验（启售中的套餐不可修改）
        if (setmeal.getStatus() == StatusConstant.ENABLE) {
            throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ON_SALE);
        }

        // 更新套餐基本信息
        BeanUtils.copyProperties(setmealDTO, setmeal);
        setmealMapper.update(setmeal);

        // 删除原有菜品关联
        setmealDishMapper.deleteBySetmealId(setmeal.getId());

        // 插入新的菜品关联
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        if (setmealDishes != null && !setmealDishes.isEmpty()) {
            setmealDishes.forEach(dish -> dish.setSetmealId(setmeal.getId()));
            setmealDishMapper.insertBatch(setmealDishes);

        }
        /**
         * 根据id查询菜品选项
         * @param id
         * @return
         */

    }

    @Override
    public List<Setmeal> list(Setmeal setmeal) {
        List<Setmeal> list = setmealMapper.list(setmeal);
        return list ;
    }

    public List<DishItemVO> getDishItemById(Long id) {
        return setmealMapper.getDishItemBySetmealId(id);
    }


}


